package cn.uniquesoft.api;

import cn.uniquesoft.service.IArticleService;
import cn.uniquesoft.service.IMyBrowseService;
import cn.uniquesoft.service.IVideosService;
import cn.uniquesoft.vo.AnswerVO;
import cn.uniquesoft.vo.MyBrowseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/api/browse")
public class ApiBrowseController {
    @Autowired
    private IMyBrowseService myBrowseService;
    @Value("${resource.pagesize}")
    private int pagesize;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IVideosService videosService;

    @RequestMapping(value = "/addbrowse")
    @ResponseBody
    public AnswerVO addbrowse(MyBrowseVO item) {
        AnswerVO answerVO = new AnswerVO();
        List<MyBrowseVO> l = this.myBrowseService.getItemsRepeat(item);
        if (l.size() > 0) {
            this.myBrowseService.removeById(l.get(0).getIid());
        }
        try {
            item.setDcreator(new Date());
            this.myBrowseService.save(item);
            int itemId = item.getIid();
            if (itemId > 0) {
                answerVO.setSuccess(true);
                answerVO.setMsg("新增成功!");
            } else {
                answerVO.setSuccess(false);
                answerVO.setMsg("新增失败!");
            }
            answerVO.setData(itemId);
        } catch (Exception e) {
            answerVO.setSuccess(false);
            answerVO.setMsg("新增失败," + e.getMessage());
        }

        return answerVO;
    }



    @RequestMapping(value = "/getMyBrowse")
    @ResponseBody
    public  List<MyBrowseVO>  getMyBrowse(int iid, int iuserid, String option) {

        List<MyBrowseVO> itemList = new ArrayList<>();
        MyBrowseVO item = new MyBrowseVO();
        item.setIid(iid);
        item.setIuserid(iuserid);
        item.setPageSize(this.pagesize);
        if(option.equals("down")){
            if(iid==0){
                itemList =   this.myBrowseService.getItemsFirst(item);
            }else{
                itemList =   this.myBrowseService.findListDown(item);
            }

        }else {
            itemList = this.myBrowseService.findListUp(item);
        }
        for(MyBrowseVO m : itemList){
            if(m.getItype()==1){
                m.setCname(this.articleService.findOneById(m.getIfileid()).getCtitle());
            }else{
                m.setCname(this.videosService.findOneById(m.getIfileid()).getCtitle());
            }
        }
        return itemList;

    }
}
